package main

import (
	"fmt"
	"github.com/veandco/go-sdl2/img"
	"github.com/veandco/go-sdl2/sdl"
)

const (
	KEY_PRESS_SURFACE_DEFAULT = iota
	KEY_PRESS_SURFACE_UP
	KEY_PRESS_SURFACE_DOWN
	KEY_PRESS_SURFACE_LEFT
	KEY_PRESS_SURFACE_RIGHT
	KEY_PRESS_SURFACE_TOTAL
)

var pressSurface [KEY_PRESS_SURFACE_TOTAL]*sdl.Surface

func init() {
	pressSurface[KEY_PRESS_SURFACE_DEFAULT] = loadSurface("../asserts/image/press.bmp")
	pressSurface[KEY_PRESS_SURFACE_UP] = loadSurface("../asserts/image/up.bmp")
	pressSurface[KEY_PRESS_SURFACE_DOWN] = loadSurface("../asserts/image/down.bmp")
	pressSurface[KEY_PRESS_SURFACE_RIGHT] = loadSurface("../asserts/image/right.bmp")
	pressSurface[KEY_PRESS_SURFACE_LEFT] = loadSurface("../asserts/image/left.bmp")
}

func loadSurface(path string) *sdl.Surface {
	img, err := img.Load(path)
	if err != nil {
		panic(err)
	}
	return img
}

func main() {
	sdl.Init(sdl.INIT_EVERYTHING)
	defer sdl.Quit()

	window, _ := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		670, 620, sdl.WINDOW_SHOWN)
	defer window.Destroy()

	surface, _ := window.GetSurface()
	defer surface.Free()
	surface.FillRect(nil, sdl.MapRGB(surface.Format, 0x0, 0x0, 0x0))

	curSurface := pressSurface[KEY_PRESS_SURFACE_DEFAULT]
	curSurface.BlitScaled(nil, surface, &sdl.Rect{X: 0, Y: 0, W: 52, H: 52})

	window.UpdateSurface()

	running := true
	for running {
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch t := event.(type) {
			case *sdl.QuitEvent:
				println("Quit")
				running = false
				break
			case *sdl.KeyboardEvent:
				switch t.Keysym.Sym {
				case sdl.K_UP:
					curSurface = pressSurface[KEY_PRESS_SURFACE_UP]
				case sdl.K_DOWN:
					curSurface = pressSurface[KEY_PRESS_SURFACE_DOWN]
				case sdl.K_LEFT:
					curSurface = pressSurface[KEY_PRESS_SURFACE_LEFT]
				case sdl.K_RIGHT:
					curSurface = pressSurface[KEY_PRESS_SURFACE_RIGHT]
				}
			}
		}
		curSurface.Blit(nil, surface, nil)
		window.UpdateSurface()
		sdl.Delay(16)
	}
	stop()
}

func stop() {
	fmt.Println("game stop")
	for i := 0; i < KEY_PRESS_SURFACE_TOTAL; i++ {
		pressSurface[i].Free()
	}
}
